<?php

class App_AccessList
{
	const ROLE_GUEST = 'guest';
	const ROLE_MEMBER = 'MB';
    const ROLE_ADMIN = 'SA'; // System Administrator

    protected static $_instance = null;
	protected $_acl = null;

	/**
    * Singleton pattern implementation makes "new" unavailable
    *
    */
    private function __construct()  {

		$this->_acl = new Zend_Acl();

		// define our possible user groups
		$this->_acl->addRole(new Zend_Acl_Role(self::ROLE_GUEST));

		// members have at least same access as guest
		$this->_acl->addRole(new Zend_Acl_Role(self::ROLE_MEMBER), array(self::ROLE_GUEST));
		
		// admins have at least same access as member
        $this->_acl->addRole(new Zend_Acl_Role(self::ROLE_ADMIN), array(self::ROLE_MEMBER));

		// define our modules as resources.
        $module = new Zend_Acl_Resource('frontend');
		$this->_acl->add($module);        
		// define our restricted controllers as resources.		
		$this->_acl->add(new Zend_Acl_Resource('frontend/index'));
		$this->_acl->add(new Zend_Acl_Resource('frontend/member'));
		$this->_acl->add(new Zend_Acl_Resource('frontend/donation'));
		$this->_acl->add(new Zend_Acl_Resource('frontend/election'));
		$this->_acl->add(new Zend_Acl_Resource('frontend/project'));
		
		// allow a guest access to our resources
		$this->_acl->allow(self::ROLE_GUEST, 'frontend/index');
		$this->_acl->allow(self::ROLE_GUEST, 'frontend/donation', array('ipn'));
		$this->_acl->allow(self::ROLE_GUEST, 'frontend/election', array('run'));
		// allow a member access to our resources
		$this->_acl->allow(self::ROLE_MEMBER, 'frontend/member');
		$this->_acl->allow(self::ROLE_MEMBER, 'frontend/donation');
		$this->_acl->allow(self::ROLE_MEMBER, 'frontend/election');
		$this->_acl->allow(self::ROLE_MEMBER, 'frontend/project');		
    }

	/**
     * Returns an instance of App_AccessControl
     *
     */
    private static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

	/**
     * Determines if the given role is allowed access to the resource
     *
     */
	public static function isAllowed($role, $resource, $privilege)
	{
		$inst = App_AccessList::getInstance();

		if (!$inst->_acl->has($resource)) {
			$resource = null;
		}

		return $inst->_acl->isAllowed($role, $resource, $privilege);
	}

    /**
     * Allows access to the given resource
     *
     */
	public static function getResource($resource)
	{
		$inst = App_AccessList::getInstance();

        if ($inst->_acl->has($resource)){
            return $inst->_acl->get($resource);
        }
        return null; // return null if not found
	}


}